package com.leozhang.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.DateTime;
import org.apache.commons.cli.*;
// import org.apache.http.HttpEntity;
// import org.apache.http.HttpResponse;
// import org.apache.http.client.methods.HttpPost;
// import org.apache.http.entity.StringEntity;
// import org.apache.http.impl.client.HttpClients;
// import org.apache.http.impl.client.CloseableHttpClient;
// import org.apache.http.impl.client.CloseableHttpResponse;

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

import com.leozhang.utils.RsaUtil;

public class PTMCLicenseGenerator {
    private static final String PRIVATE_KEY_PATH = "keys/ptmc_private_pkcs8.der";

    public static void main(String[] args) {
        Options options = new Options();

        options.addOption("i", "input", true, "License 文件路径");
        options.addOption("o", "output", true, "输出证书文件路径");
        options.addOption("d", "licenseDays", true, "License 过期天数 (默认 100)");
        options.addOption("m", "maintenanceDays", true, "维护期天数 (默认 100)");
        options.addOption("c", "customerName", true, "客户名称");
        options.addOption("t", "type", true, "许可证类型 (默认 enterprise)");
        options.addOption("u", "userNum", true, "用户数量 (默认 1000)");
        options.addOption("v", "enableVpn", true, "是否启用 VPN (默认 1)");
        options.addOption("w", "workstationNum", true, "工作站数量 (默认 1000)");

        CommandLineParser parser = new DefaultParser();
        try {
            CommandLine cmd = parser.parse(options, args);

            if (!cmd.hasOption("i") || !cmd.hasOption("o")) {
                System.out.println("使用方式: java LicenseGenerator -i <licenseFilePath> -o <outputFilePath> [可选参数]");
                new HelpFormatter().printHelp("LicenseGenerator", options);
                return;
            }

            String licenseFilePath = cmd.getOptionValue("i");
            String outputFilePath = cmd.getOptionValue("o");

            // 读取 License 文件内容
            String licenseContent = new String(Files.readAllBytes(Paths.get(licenseFilePath))).trim();
            // System.out.println("License content: " + licenseContent);

            // 解密 License 内容
            String decryptedData = RsaUtil.decryptByPrivateKeyFile(PRIVATE_KEY_PATH, licenseContent);
            JSONObject lic = JSONObject.parseObject(decryptedData);

            // 获取命令行参数或默认值
            int licenseDays = Integer.parseInt(cmd.getOptionValue("d", "100"));
            int maintenanceDays = Integer.parseInt(cmd.getOptionValue("m", "100"));
            String customerName = cmd.getOptionValue("c", "LeoZhang");
            String type = cmd.getOptionValue("t", "enterprise");
            int userNum = Integer.parseInt(cmd.getOptionValue("u", "1000"));
            boolean enableVpn = Integer.parseInt(cmd.getOptionValue("v", "1")) == 1;
            int workstationNum = Integer.parseInt(cmd.getOptionValue("w", "1000"));

            // 生成新的 License 数据
            Map<String, Object> jsonMap = new HashMap<>();
            DateTime dateTime = DateUtil.date();
            jsonMap.put("issuedDate", DateUtil.format(dateTime, "yyyyMMddHHmmss"));
            jsonMap.put("expiredDate", DateUtil.format(DateUtil.offsetDay(dateTime, licenseDays), "yyyyMMddHHmmss"));
            jsonMap.put("maintenanceStartDate", DateUtil.format(dateTime, "yyyyMMddHHmmss"));
            jsonMap.put("maintenanceEndDate",
                    DateUtil.format(DateUtil.offsetDay(dateTime, maintenanceDays), "yyyyMMddHHmmss"));
            jsonMap.put("type", type);
            jsonMap.put("productSerialNumber", lic.getString("productSerialNumber"));
            jsonMap.put("userNum", userNum);
            jsonMap.put("enableVpn", enableVpn);
            jsonMap.put("workstationNum", workstationNum);
            jsonMap.put("customerName", customerName);

            // 加密 License 数据
            String encryptedData = RsaUtil.encryptByPriKeyFile(PRIVATE_KEY_PATH, JSON.toJSONString(jsonMap));

            // 将证书内容写入文件
            try (FileWriter writer = new FileWriter(outputFilePath)) {
                writer.write(encryptedData);
            }

            // System.out.println("证书生成成功，已保存至：" + outputFilePath);
        } catch (ParseException e) {
            System.err.println("命令行参数解析失败：" + e.getMessage());
        } catch (IOException e) {
            System.err.println("读取 License 文件失败：" + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("证书生成失败！");
        }
    }

    // private static boolean uploadLicense(String licenseContent) {
    //     try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    //         HttpPost postRequest = new HttpPost(AUTH_URL);

    //         // 设置请求体
    //         StringEntity entity = new StringEntity("{\"content\":\"" + licenseContent + "\"}");
    //         postRequest.setEntity(entity);
    //         postRequest.setHeader("Content-Type", "application/json");

    //         try (CloseableHttpResponse response = httpClient.execute(postRequest)) {
    //             HttpEntity responseEntity = response.getEntity();
    //             String responseString = new String(responseEntity.getContent().readAllBytes());

    //             // 简单检查授权是否成功（根据实际接口返回判断）
    //             if (response.getStatusLine().getStatusCode() == 200) {
    //                 System.out.println("授权成功： " + responseString);
    //                 return true;
    //             } else {
    //                 System.err.println("授权失败： " + responseString);
    //                 return false;
    //             }
    //         }
    //     } catch (Exception e) {
    //         e.printStackTrace();
    //         System.err.println("调用授权接口失败！");
    //         return false;
    //     }
    // }
}
